package org.orz.story.gateway.filter;

import cn.hutool.core.collection.CollUtil;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.orz.cloud.common.exception.SystemErrorCode;
import org.orz.cloud.common.result.ResultDTO;
import org.orz.story.gateway.clients.PmsClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.nio.charset.StandardCharsets;

@Slf4j
@Component
public class AuthGlobalFilter implements GlobalFilter  {
    @Autowired
    private PmsClient pmsClient;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        HttpHeaders headers = exchange.getRequest().getHeaders();
        String workbench = CollUtil.isEmpty(headers.get("workbench")) ? null : headers.get("workbench").get(0);
        String authorization = CollUtil.isEmpty(headers.get("authorization")) ? null : headers.get("authorization").get(0);

        ServerHttpResponse response = exchange.getResponse();
        try {
            ResultDTO result = pmsClient.doAuth(exchange.getRequest().getPath().toString(), workbench, authorization);
            if(!result.getSuccess()){
                return handleResponse(result, response);
            }
        } catch (Exception e){
            log.error("pms error.", e);
            return handleResponse(ResultDTO.fail(SystemErrorCode.SERVER_ERROR), response);
        }
        return chain.filter(exchange);
    }

    private Mono<Void> handleResponse(ResultDTO resultDTO, ServerHttpResponse response){
        byte[] bits = JSON.toJSONString(resultDTO).getBytes(StandardCharsets.UTF_8);
        DataBuffer buffer = response.bufferFactory().wrap(bits);
        response.setStatusCode(HttpStatus.OK);
        response.getHeaders().add("Content-Type", "application/json;charset=UTF-8");
        return response.writeWith(Mono.just(buffer));
    }
}
